package com.autoscript.ext.xmldata.pdm;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import com.autoscript.ext.xmldata.dbmodel.DBModel;
import com.autoscript.ext.xmldata.dbmodel.IDBModel;
import com.autoscript.ext.xmldata.dbmodel.ITableModel;
import com.autoscript.ext.xmldata.pdm.parse.IPdmParse;
import com.autoscript.ext.xmldata.pdm.parse.PdmParse;
import com.autoscript.ui.helper.FileCtrlUtils;
import com.autoscript.ui.helper.StringHelper;

/**
 * Pdm对话框
 *
 * 作者:龙色波 日期:2013-10-22
 */
public class PdmDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3777251102369744024L;
	private final JPanel contentPanel = new JPanel();
	private JTextField textField;
	private JList leftTableList;
	private JList rightTableList;
	private DefaultListModel leftListModel;
	protected IDBModel leftPdmModel;
	protected IDBModel rightPdmModel;
	private DefaultListModel rightListModel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			PdmDialog dialog = new PdmDialog(null, "选择PDM文件", true);
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
			dialog.setLocationRelativeTo(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化布局
	 */
	public void initLayout() {
		getContentPane().setLayout(new BorderLayout());
		// 创建top panel
		JPanel topPanel = createTopPanel();
		// 创建中间 panel
		JPanel centerPanel = createMiddlePanel();
		// 创建底部panel
		JPanel bottomPanel = createBottomPanel();
		getContentPane().add(topPanel, BorderLayout.NORTH);
		getContentPane().add(centerPanel, BorderLayout.CENTER);
		getContentPane().add(bottomPanel, BorderLayout.SOUTH);
	}

	/**
	 * 创建底部面板
	 * 
	 * @return
	 */
	private JPanel createBottomPanel() {
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new BorderLayout());
		JPanel subPane = new JPanel();
		subPane.setLayout(new FlowLayout());
		{
			JButton okButton = new JButton("确定");
//			okButton.setAlignmentX(Component.LEFT_ALIGNMENT);
			okButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// 检查是否选择表
					if (rightPdmModel == null || rightPdmModel.getTableModels() == null
							|| rightPdmModel.getTableModels().size() == 0) {
						JOptionPane.showMessageDialog(PdmDialog.this, "请选择表名!");
						return;
					}
					PdmDialog.this.dispose();
				}
			});
			okButton.setActionCommand("OK");
			subPane.add(okButton);
		}
		{
			JButton cancelButton = new JButton("取消");
			cancelButton.setAlignmentX(Component.LEFT_ALIGNMENT);
			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if (rightPdmModel != null && rightPdmModel.getTableModels() != null
							&& rightPdmModel.getTableModels().size() > 0) {
						rightPdmModel.getTableModels().clear();
					}
					PdmDialog.this.dispose();
				}
			});
			cancelButton.setActionCommand("Cancel");
			subPane.add(cancelButton);
		}
		buttonPane.add(subPane,BorderLayout.EAST);
		return buttonPane;
	}

	/**
	 * 创建底部panel
	 * 
	 * @return
	 */
	private JPanel createMiddlePanel() {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		// 创建可选择表面板
		JPanel allowSelectTabPanel = createAllowSelectTabPanel();
		// 创建中间按钮面板
		JPanel buttonPanel = createButtonPanel();
		// 创建已选择表面板
		JPanel selectedTabPanel = createSeletedTabPanel();
		panel.add(allowSelectTabPanel);
		panel.add(buttonPanel);
		panel.add(selectedTabPanel);
		return panel;
	}

	/**
	 * 创建已选择表面板
	 * 
	 * @return
	 */
	private JPanel createSeletedTabPanel() {
		JLabel filterLable = new JLabel("已选择的表：");
		filterLable.setAlignmentY(TOP_ALIGNMENT);

		JPanel panel = new JPanel();
		BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
		panel.setLayout(layout);
		// 创建底部panel
		rightTableList = new JList();
		JScrollPane rightListPane;
		rightListPane = new JScrollPane(rightTableList);
		rightListPane.setAlignmentY(TOP_ALIGNMENT);
		panel.add(rightListPane);
		return panel;
	}

	/**
	 * 创建按钮面板
	 * 
	 * @return
	 */
	private JPanel createButtonPanel() {
		JPanel panel = new JPanel();
		BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
		panel.setLayout(layout);

		JButton delButton = new JButton("< ");
		delButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectIndexs[] = rightTableList.getSelectedIndices();
				for (int i = selectIndexs.length - 1; i >= 0; i--) {
					leftListModel.addElement(rightListModel.get(selectIndexs[i]));
					leftPdmModel.getTableModels().add((ITableModel) rightListModel.get(selectIndexs[i]));
					rightPdmModel.getTableModels().remove(selectIndexs[i]);
					rightListModel.remove(selectIndexs[i]);
				}
				if (selectIndexs != null && selectIndexs.length > 0) {
					leftTableList.setModel(leftListModel);
					rightTableList.setModel(rightListModel);
				}
			}
		});
		JButton delAllButton = new JButton("<<");
		delAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int count;
				count = rightListModel.size();
				for (int i = count - 1; i >= 0; i--) {
					leftListModel.addElement(rightListModel.get(i));
					leftPdmModel.getTableModels().add((ITableModel) rightListModel.get(i));
					rightPdmModel.getTableModels().remove(i);
					rightListModel.remove(i);
				}
				leftTableList.setModel(leftListModel);
				rightTableList.setModel(rightListModel);
			}
		});
		JButton addButton = new JButton("> ");
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectIndexs[] = leftTableList.getSelectedIndices();
				for (int i = selectIndexs.length - 1; i >= 0; i--) {
					rightListModel.addElement(leftListModel.get(selectIndexs[i]));
					rightPdmModel.getTableModels().add((ITableModel) leftListModel.get(selectIndexs[i]));
					leftPdmModel.getTableModels().remove(selectIndexs[i]);
					leftListModel.remove(selectIndexs[i]);
				}
				if (selectIndexs != null && selectIndexs.length > 0) {
					rightTableList.setModel(rightListModel);
					leftTableList.setModel(leftListModel);
					rightTableList.updateUI();
					leftTableList.updateUI();
				}
			}
		});
		JButton addAllButton = new JButton(">>");
		addAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int count;
				count = leftListModel.size();
				for (int i = count - 1; i >= 0; i--) {
					rightListModel.addElement(leftListModel.get(i));
					rightPdmModel.getTableModels().add((ITableModel) leftListModel.get(i));
					leftPdmModel.getTableModels().remove(i);
					leftListModel.remove(i);
				}
				leftTableList.setModel(leftListModel);
				rightTableList.setModel(rightListModel);
			}
		});
		panel.add(delButton);
		panel.add(Box.createRigidArea(new Dimension(15, 15)));// 中间添加一个看不见的rigidArea
		panel.add(delAllButton);
		panel.add(Box.createRigidArea(new Dimension(15, 15)));// 中间添加一个看不见的rigidArea
		panel.add(addButton);
		panel.add(Box.createRigidArea(new Dimension(15, 15)));// 中间添加一个看不见的rigidArea
		panel.add(addAllButton);

		return panel;
	}

	/**
	 * 创建允许选择表面板
	 * 
	 * @return
	 */
	private JPanel createAllowSelectTabPanel() {
		JPanel topPanel = new JPanel();
		BoxLayout xlayout = new BoxLayout(topPanel, BoxLayout.X_AXIS);
		topPanel.setLayout(xlayout);
		JLabel filterLable = new JLabel("可选表名过滤：");
		filterLable.setAlignmentX(LEFT_ALIGNMENT);
		topPanel.add(filterLable);
		JTextField textField = new JTextField();
		textField.setColumns(10);
		textField.setAlignmentX(LEFT_ALIGNMENT);
		topPanel.add(textField);
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				JTextField text = (JTextField) e.getSource();
				filterTable(leftPdmModel, text.getText());
			}
		});
		JPanel borderPanel = new JPanel();
		
		borderPanel.setLayout(new BorderLayout());
		JPanel panel = new JPanel();
		BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
		panel.setLayout(layout);
		// 创建底部panel
		leftTableList = new JList();
		JScrollPane leftListPane;
		leftListPane = new JScrollPane(leftTableList);
		leftListPane.setAlignmentY(TOP_ALIGNMENT);
		borderPanel.add(topPanel,BorderLayout.NORTH);
		panel.add(leftListPane);
		borderPanel.add(panel,BorderLayout.CENTER);
		
		
		return borderPanel;
	}

	/**
	 * 创建头部panel
	 * 
	 * @return
	 */
	private JPanel createTopPanel() {
		JPanel panel = new JPanel();
		BoxLayout layout = new BoxLayout(panel, BoxLayout.X_AXIS);
		panel.setLayout(layout);
		JLabel lblNewLabel = new JLabel("Pdm文件名：");
//		lblNewLabel.setBounds(10, 14, 66, 15);
		lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
		panel.add(lblNewLabel);
		{
			textField = new JTextField();
//			textField.setBounds(86, 11, 290, 21);
			panel.add(textField);
			textField.setColumns(10);
			textField.setHorizontalAlignment(SwingConstants.LEFT);
			textField.addFocusListener(new FocusListener() {

				@Override
				public void focusGained(FocusEvent e) {
					// TODO Auto-generated method stub
				}

				@Override
				public void focusLost(FocusEvent e) {
					// 失去焦点时，如果没有装入pdm，则装入
					if (!StringHelper.isEmpty(textField.getText()) && FileCtrlUtils.isExists(textField.getText())) {
						if (leftPdmModel == null || leftPdmModel.getTableModels().size() == 0) {
							loadPdmTables(textField.getText());
						}
					}
				}

			});
		}
		JButton btnNewButton = new JButton("...");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				FileDialog dlg;
				dlg = new FileDialog(PdmDialog.this, "PDM文件", FileDialog.LOAD);
				// dlg.setFilenameFilter(new CustFileNameFilter(".pdm"));
				dlg.setVisible(true);
				String fileName;
				fileName = dlg.getDirectory() + dlg.getFile();
				if (!StringHelper.isEmpty(dlg.getFile())) {
					textField.setText(fileName);
					loadPdmTables(fileName);
				}
			}

		});
		btnNewButton.setAlignmentX(LEFT_ALIGNMENT);
		panel.add(btnNewButton);
		return panel;
	}

	/**
	 * Create the dialog.
	 */
	public PdmDialog(Frame frame, String title, boolean modal) {
		super(frame, title, modal);
		setSize(500, 391);
		this.setResizable(true);
		center();
		
		initLayout();
	}
	/**
	 * 居中显示
	 */
	private void center() {
		int windowWidth = this.getWidth(); //获得窗口宽

		int windowHeight = this.getHeight(); //获得窗口高

		Toolkit kit = Toolkit.getDefaultToolkit(); //定义工具包

		int screenWidth = kit.getScreenSize().width; //获取屏幕的宽

		int screenHeight = kit.getScreenSize().height; //获取屏幕的高

		this.setLocation(screenWidth/2 - windowWidth/2, screenHeight/2 - windowHeight/2);
	}

	protected void fillLeftList(IDBModel model) {
		leftListModel = new DefaultListModel();
		for (ITableModel tableModel : model.getTableModels()) {
			leftListModel.addElement(tableModel);
		}
		leftTableList.setModel(leftListModel);
	}

	protected void clearRightList() {
		rightListModel = new DefaultListModel();
		rightTableList.setModel(rightListModel);

	}

	protected void clearLeftList() {
		leftListModel = new DefaultListModel();
		leftTableList.setModel(leftListModel);

	}

	/**
	 * 创建左边面板
	 * 
	 * @return
	 */
	private JPanel createLeftPanel() {
		GridBagLayout gridbag = new GridBagLayout();
		gridbag.rowWeights = new double[] { 0.0, 0.0, 1.0 };
		gridbag.columnWeights = new double[] { 1.0, 1.0 };
		GridBagConstraints c = new GridBagConstraints();

		JPanel leftPanel = new JPanel();

		leftPanel.setLayout(gridbag);
		JLabel noSelectTabLable = new JLabel("未选择的表:");
		GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
		gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
		gbc_lblNewLabel.gridwidth = 2;
		gbc_lblNewLabel.fill = GridBagConstraints.HORIZONTAL;
		gbc_lblNewLabel.gridx = 0;
		gbc_lblNewLabel.gridy = 0;
		leftPanel.add(noSelectTabLable, gbc_lblNewLabel);
		JLabel filterLable = new JLabel("表名过滤：");
		GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
		gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
		gbc_lblNewLabel_1.anchor = GridBagConstraints.WEST;
		gbc_lblNewLabel_1.gridx = 0;
		gbc_lblNewLabel_1.gridy = 1;
		leftPanel.add(filterLable, gbc_lblNewLabel_1);
		JTextField textField = new JTextField();
		textField.setColumns(20);
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				JTextField text = (JTextField) e.getSource();
				filterTable(leftPdmModel, text.getText());
			}
		});
		GridBagConstraints gbc_textField = new GridBagConstraints();
		gbc_textField.anchor = GridBagConstraints.WEST;
		gbc_textField.insets = new Insets(0, 0, 5, 0);
		gbc_textField.fill = GridBagConstraints.HORIZONTAL;
		gbc_textField.gridx = 1;
		gbc_textField.gridy = 1;
		leftPanel.add(textField, gbc_textField);

		leftTableList = new JList();
		JScrollPane leftListPane;
		leftListPane = new JScrollPane(leftTableList);
		GridBagConstraints gbc_list = new GridBagConstraints();
		gbc_list.gridwidth = 2;
		gbc_list.insets = new Insets(0, 0, 0, 5);
		gbc_list.fill = GridBagConstraints.BOTH;
		gbc_list.gridx = 0;
		gbc_list.gridy = 2;
		leftPanel.add(leftListPane, gbc_list);
//		leftPanel.add(leftListPane,"Center");
		return leftPanel;
	}

	/**
	 * 过滤表
	 * 
	 * @param leftPdmModel2
	 * @param text
	 */
	protected void filterTable(IDBModel leftPdmModel2, String text) {
		leftListModel = new DefaultListModel();
		for (ITableModel tableModel : leftPdmModel2.getTableModels()) {
			if (!StringHelper.isEmpty(text)) {
				boolean bFound = false;
				// 忽略大小写
				String code = tableModel.getCode().toLowerCase();
				text = text.toLowerCase();
				if (text.endsWith("*")) {
					if (code.startsWith(text.substring(0, text.length() - 1))) {
						leftListModel.addElement(tableModel);
						bFound = true;
					}
				} else if (text.startsWith("*")) {
					if (code.endsWith(text.substring(1, text.length()))) {
						leftListModel.addElement(tableModel);
						bFound = true;
					}
				} else if (code.equals(text)) {
					leftListModel.addElement(tableModel);
					bFound = true;
				}
				// 如果没有找到，尝试查找中文字段
				if (!bFound) {
					String name = tableModel.getName();
					text = text.toLowerCase();
					if (text.endsWith("*")) {
						if (name.startsWith(text.substring(0, text.length() - 1))) {
							leftListModel.addElement(tableModel);
						}
					} else if (text.startsWith("*")) {
						if (name.endsWith(text.substring(1, text.length()))) {
							leftListModel.addElement(tableModel);
						}
					} else if (name.equals(text)) {
						leftListModel.addElement(tableModel);
					}
				}
			} else {
				leftListModel.addElement(tableModel);
			}
		}
		leftTableList.setModel(leftListModel);
	}

	/**
	 * 创建右边面板
	 * 
	 * @return
	 */
	private JPanel createRightPanel() {
		JPanel rightPanel = new JPanel();
		rightPanel.setLayout(new BorderLayout(0, 0));

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new GridLayout(4, 1, 10, 30));
		rightPanel.add(buttonPanel, BorderLayout.WEST);
		JButton delButton = new JButton("<");
		delButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectIndexs[] = rightTableList.getSelectedIndices();
				for (int i = selectIndexs.length - 1; i >= 0; i--) {
					leftListModel.addElement(rightListModel.get(selectIndexs[i]));
					leftPdmModel.getTableModels().add((ITableModel) rightListModel.get(selectIndexs[i]));
					rightPdmModel.getTableModels().remove(selectIndexs[i]);
					rightListModel.remove(selectIndexs[i]);
				}
				if (selectIndexs != null && selectIndexs.length > 0) {
					leftTableList.setModel(leftListModel);
					rightTableList.setModel(rightListModel);
				}
			}
		});
		JButton delAllButton = new JButton("<<");
		delAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int count;
				count = rightListModel.size();
				for (int i = count - 1; i >= 0; i--) {
					leftListModel.addElement(rightListModel.get(i));
					leftPdmModel.getTableModels().add((ITableModel) rightListModel.get(i));
					rightPdmModel.getTableModels().remove(i);
					rightListModel.remove(i);
				}
				leftTableList.setModel(leftListModel);
				rightTableList.setModel(rightListModel);
			}
		});
		JButton addButton = new JButton(">");
		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int selectIndexs[] = leftTableList.getSelectedIndices();
				for (int i = selectIndexs.length - 1; i >= 0; i--) {
					rightListModel.addElement(leftListModel.get(selectIndexs[i]));
					rightPdmModel.getTableModels().add((ITableModel) leftListModel.get(selectIndexs[i]));
					leftPdmModel.getTableModels().remove(selectIndexs[i]);
					leftListModel.remove(selectIndexs[i]);
				}
				if (selectIndexs != null && selectIndexs.length > 0) {
					rightTableList.setModel(rightListModel);
					leftTableList.setModel(leftListModel);
					rightTableList.updateUI();
					leftTableList.updateUI();
				}
			}
		});
		JButton addAllButton = new JButton(">>");
		addAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int count;
				count = leftListModel.size();
				for (int i = count - 1; i >= 0; i--) {
					rightListModel.addElement(leftListModel.get(i));
					rightPdmModel.getTableModels().add((ITableModel) leftListModel.get(i));
					leftPdmModel.getTableModels().remove(i);
					leftListModel.remove(i);
				}
				leftTableList.setModel(leftListModel);
				rightTableList.setModel(rightListModel);
			}
		});
		buttonPanel.add(delButton);
		buttonPanel.add(delAllButton);
		buttonPanel.add(addButton);
		buttonPanel.add(addAllButton);
		rightTableList = new JList();
		JScrollPane listPane = new JScrollPane(rightTableList);
		rightPanel.add(listPane);

		JPanel panel = new JPanel();
		rightPanel.add(panel, BorderLayout.NORTH);

		JLabel label_1 = new JLabel("已选择的表:");
		panel.add(label_1);
		label_1.setBounds(179, 42, 101, 15);

//		rightPanel.add(buttonPanel, "West");
//		rightPanel.add(listPane,"Center");
		return rightPanel;
	}

	public IDBModel getRightPdmModel() {
		return rightPdmModel;
	}

	private void loadPdmTables(String fileName) {
		try {
			IPdmParse parse = new PdmParse();
			leftPdmModel = parse.parse(fileName);
			rightPdmModel = new DBModel();
			// 为了方便生成xml，把所有的参考模型加入到右边pdm模型
			rightPdmModel.setReferenceModels(leftPdmModel.getReferenceModels());
			rightPdmModel.setDomainModels(leftPdmModel.getDomainModels());
			// 清空左边列表
			clearLeftList();
			// 清空右边列表
			clearRightList();
			// 填充左边列表
			fillLeftList(leftPdmModel);
		} catch (Exception e1) {
			e1.printStackTrace();
			JOptionPane.showMessageDialog(PdmDialog.this, e1.getMessage());
		}
	}
}
